<!-- 邮件资源 -->
<template>
  <div  class="dashboard-editor-container">
    <el-tabs type="border-card" @tab-click="tabClick">
      <el-tab-pane label="基本参数">
        <el-row style="background: #fff; ">
          <div class="content parameType" style="width: 100%">
            <div class="certification top"  style="width: 100%">
              <div class="toptitle">
                <div class="title">群发参数配置</div>
                <!-- <i :class="!formshow ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"></i> -->
                <!-- <div class="tabclick"  @click="formshow = !formshow" >
                  <div class="tabitem">
                    <span><i :class="formshow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
                  </div>
                </div> -->
              </div>
              <el-form label-width="200px" v-show="formshow">
                <el-col :xs="24" :sm="24" :lg="24">
                  <el-form-item label="公司名称:">
                    <el-input v-model="emailForm.CorpName"  style="width:400px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="24">
                  <el-form-item label="公司网址:">
                    <el-input v-model="emailForm.WebSite"  style="width:400px" oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')"></el-input>
                  </el-form-item>
                  <p>（内嵌图片点击是自动跳转到配置的公司网址）</p>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="24">
                  <el-form-item label="发件人昵称:">
                    <el-input v-model="emailForm.SendNickName" style="width:400px"></el-input>
                  </el-form-item>
                  <p>发件人显示昵称：<el-switch v-model="emailForm.IsAddCorpNameToSendAccount" active-color="#2491fc" inactive-color="#ccc" :active-value = 1 :inactive-value = 0></el-switch></p>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="24">
                  <el-form-item label="邮件推广执行时间点:">
                    <el-select v-model="emailForm.ExecHours"  style="width:400px">
                      <el-option value=0 label="0"></el-option>
                      <el-option v-for="item in 24" :key="item" :value=item :label="item+':00'"></el-option>
                    </el-select>
                  </el-form-item>
                  <p>（0表示不限制时间点，否则为配置的时间点执行）</p>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="24">
                  <el-form-item label="邮件发送延迟:">
                    <el-input v-model="emailForm.SendInterval"  style="width:400px" oninput ="value=value.replace(/[^0-9]/g,'')" :maxlength="10"></el-input>
                  </el-form-item>
                  <p>（0表示不延迟，单位秒）</p>
                </el-col>
                <el-col :xs="24" :sm="24" :lg="24">
                  <!-- <el-button type="primary" @click="TestMailGlobal(emailForm)"  style="margin-left:670px">测试邮箱</el-button> -->
                  <el-button type="primary" icon="el-icon-thumb" @click="SetParamMailGlobal(emailForm)"  style="margin-left:470px">保存</el-button>
                </el-col>
              </el-form>
            </div>
          </div>
          
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="客户群体">
        <div class="parameType" style="margin: 0">
          <div style="display:flex;align-items: center;justify-content: space-between;">
            <div class="title" >目标客户群体</div>
            <el-button type="primary" icon='el-icon-circle-plus-outline' @click="addResources()">添加目标客户群体</el-button>
          </div>
          <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
            <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
            <el-table-column label="任务标识" prop="TaskID" align="left" width="120px" show-overflow-tooltip></el-table-column>
            <el-table-column label="数据来源" prop="ResType" align="left" show-overflow-tooltip>
              <template slot-scope="{row}">
                <span>{{ row.ResType === 1 ? '展会资料' : row.ResType === 2?'海关数据':'货运数据' }}</span>
                <!-- <span>{{ row.ResType === 1 ? '展会资料' : '海关数据' }}</span>
                <span>{{ row.ResType === 1 ? '展会资料' : '海关数据' }}</span> -->
              </template>
            </el-table-column>
            <el-table-column label="国家" prop="Country" align="left" show-overflow-tooltip>
              <template slot-scope="{row}">
                <span v-if="row.ResType !== 3">{{ !row.Country ? '全部' : row.Country }}</span>
                <span v-if="row.ResType === 3">——</span>
              </template>
            </el-table-column>
            <el-table-column label="详细分类" prop="Class" align="left" show-overflow-tooltip>
              <template slot-scope="{row}">
                <span v-if="row.ResType !== 3">{{ !row.Class ? '全部' : row.Class }}</span>
                <span v-if="row.ResType === 3 && row.Class !== '全部'">{{ row.Class }}/{{ row.CorpType }}</span>
                <span v-if="row.ResType === 3 && row.Class === '全部'">{{ row.Class }}</span>
              </template>
            </el-table-column>
            <el-table-column label="海关编码" prop="HSCode" align="left"  show-overflow-tooltip></el-table-column>
            <el-table-column label="企业类型" prop="CorpType" align="left"  show-overflow-tooltip>
              <template slot-scope="{row}">
                <span v-if="row.ResType !== 3">{{ row.CorpType === '11' ? '全部' : row.CorpType === '10' ? '采购商' : '供应商' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="公司职位" prop="Duty" align="left" width="200"  show-overflow-tooltip>
              <template slot-scope="{row}">
                <span>{{ row.Duty[0] === '1' ? '老板 ' : '' }}</span>
                <span>{{ row.Duty[1] === '1' ? '管理人员 ' : '' }}</span>
                <span>{{ row.Duty[2] === '1' ? '采购 ' : '' }}</span>
                <span>{{ row.Duty[3] === '1' ? '其他 ' : '' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="参展年份" prop="Year" align="left"  show-overflow-tooltip></el-table-column>
            <!-- <el-table-column label="出口商国家" prop="InCountry" align="left"  show-overflow-tooltip></el-table-column> -->
            <!-- <el-table-column label="进口商国家" prop="OutCountry" align="left"  show-overflow-tooltip></el-table-column> -->
            <el-table-column label="交易日期" prop="TransDate" align="left"  show-overflow-tooltip></el-table-column>
            <el-table-column label="完成度" prop="TransDate" align="left" width="200" show-overflow-tooltip >
              <template slot-scope="{row}" >
                <div  style="display: flex; aling-items:center;">
                  <el-progress :percentage="row.Total != 0 ? Number( row.Finish / row.Total ) * 100 : 0" :show-text="false"></el-progress>
                  <span style="margin-left:10px;">{{row.Finish}}/{{row.Total}}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="90px">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="deleteMailGlobal(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="智能群发">
        <intelligentMassSending ref="intelligentMassSending"/>
      </el-tab-pane>
      <el-tab-pane label="群发帐号">
        <massPostingAccount ref="massPostingAccount"/>
      </el-tab-pane>
      <el-tab-pane label="历史软文">
        <historicalSoftWriting ref="historicalSoftWriting"/>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false  
      :title="Action === 1 ? '添加目标群体' : '修改目标群体' "
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="50%">
      <el-form label-width="120px" :model="resourceForm" :rules="rules" ref="resourceForm">
        <el-form-item label='数据仓库:'>
          <el-radio-group v-model="resourceForm.ResType" @change="radioChange">
            <el-radio :label="1">展会资料</el-radio>
            <el-radio :label="2">海关数据</el-radio>
            <el-radio :label="3">货运数据</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='国家:' prop="Country" v-if="resourceForm.ResType === 1">
          <div style="display:flex;">
            <el-select filterable clearable v-model="resourceForm.Country" placeholder="请选择国家" style="width:100%">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="(item, index) in ExpoCountryList" :key="index" :label="item.CountryName" :value="item.CountryName"></el-option>
            </el-select>
            <el-button style="margin-left:10px;" type="primary" @click="openCountryDialog(1)">选择国家</el-button>
          </div>
        </el-form-item>
        <el-form-item label='详细分类:' prop="Class" v-if="resourceForm.ResType=== 1">
          <div style="display:flex;">
            <el-select filterable clearable v-model="resourceForm.Class" placeholder="请选择详细分类" style="width:100%">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="(item, index) in ExpoClassList" :key="index" :label="item" :value="item"></el-option>
            </el-select>
            <el-button style="margin-left:10px;" type="primary" @click="classDialog = true">选择分类</el-button>
          </div>
        </el-form-item>
        <el-form-item label='企业类型:' prop="Class" v-if="resourceForm.ResType=== 1">
          <div style="display:flex;">
            <el-select filterable clearable v-model="resourceForm.CorpType" placeholder="请选择企业类型" style="width:100%">
              <el-option label="全部" value="11"></el-option>
              <el-option label="采购商" value="10"></el-option>
              <el-option label="供应商" value="01"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label='公司职位:' v-if="resourceForm.ResType=== 1">
          <el-checkbox-group v-model="resourceForm.Duty">
            <el-checkbox label="老板"></el-checkbox>
            <el-checkbox label="管理人员"></el-checkbox>
            <el-checkbox label="采购"></el-checkbox>
            <el-checkbox label="其他"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label='参展年份:' prop="Class" v-if="resourceForm.ResType=== 1">
          <div style="display:flex;">
            <el-select filterable clearable v-model="resourceForm.Year" placeholder="请选择详细分类" style="width:100%">
              <el-option label="全部" value=""></el-option>
              <el-option v-for="item in yearList" :key= "item" :label="item" :value="item" ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label='海关HS编码:' prop="HSCode" v-if="resourceForm.ResType=== 2">
          <div style="display:flex;">
            <el-input v-model="resourceForm.HSCode" oninput ="value=value.replace(/[^0-9]/g,'')" maxlength="4" placeholder="请输入4位数字的海关HS编码"></el-input>
            <!-- <el-cascader
              popper-class="popper-class" :popper-append-to-body="false"
              filterable
              v-model="resourceForm.HSCode"
              :options="HSCodeList"
              :props="{ label:'Name', value:'HsCode', children: 'Child', expandTrigger: 'hover' }"
              @change="handleChange">
            </el-cascader> -->
            <el-button style="margin-left:10px;" type="primary" @click="viewClassificationCodes">查看分类编码</el-button>
          </div>
        </el-form-item>
        <el-form-item label='国家:'  prop="Country" v-if="resourceForm.ResType=== 2">
          <div style="display:flex;">
            <el-select filterable clearable v-model="resourceForm.Country" placeholder="请选择国家" style="width:100%">
              <el-option v-for="(item, index) in ExpoCountryList" :key="index" :label="item.CountryName" :value="item.CountryName"></el-option>
            </el-select>
            <el-button style="margin-left:10px;" type="primary" @click="openCountryDialog(2)">选择国家</el-button>
          </div>
        </el-form-item>
        <!-- <el-form-item label='进口商国家:'  prop="InCountry" v-if="resourceForm.ResType=== 2">
          <div style="display:flex;">
            <el-select filterable clearable v-model="resourceForm.InCountry" placeholder="请选择进口商国家" style="width:100%">
              <el-option v-for="(item, index) in ExpoCountryList" :key="index" :label="item.CountryName" :value="item.CountryName"></el-option>
            </el-select>
            <el-button style="margin-left:10px;" type="primary" @click="openCountryDialog(3)">查看进口国家</el-button>
          </div>
        </el-form-item> -->
        <el-form-item label='企业类型:' prop="Class" v-if="resourceForm.ResType=== 2">
          <div style="display:flex;">
            <el-select filterable clearable v-model="resourceForm.CorpType" placeholder="请选择企业类型" style="width:100%">
              <el-option label="全部" value="11"></el-option>
              <el-option label="采购商" value="10"></el-option>
              <el-option label="供应商" value="01"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label='公司职位:' v-if="resourceForm.ResType=== 2">
          <el-checkbox-group v-model="resourceForm.Duty">
            <el-checkbox label="老板"></el-checkbox>
            <el-checkbox label="管理人员"></el-checkbox>
            <el-checkbox label="采购"></el-checkbox>
            <el-checkbox label="其他"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!--ResType == 3  -->
        <el-form-item label='货运名称:' prop="Cname" v-if="resourceForm.ResType=== 3">
          <div style="display:flex;">
            <!-- <el-input v-model="CargoForm.Cname" oninput ="value=value.replace(/[^0-9]/g,'')" maxlength="4" placeholder="请输入货运的名称"></el-input>
            <el-button style="margin-left:10px;" type="primary" @click="viewClassCargo">查看货运分类</el-button> -->
            <el-cascader  :placeholder="CargoList[0].value" style="width:100%" v-model='value'  :options="CargoList" @change="handleChanges" :props="{ label:'Name',children: 'Child', expandTrigger: 'hover'  }"  :show-all-levels="control"></el-cascader>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" v-if="resourceForm.ResType === 3">
        <el-button type="primary"  @click="submitCargo">确 定</el-button>
        <el-button type="info" @click="concelCargo">取 消</el-button>
      </span>
      <span slot="footer" class="dialog-footer" v-if="resourceForm.ResType !== 3">
        <el-button type="primary"  @click="submit">确 定</el-button>
        <el-button type="info" @click="concelCargo">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="请选择要导入的人员(已自动清除重复邮箱和错误邮箱)"
      ref="multipleTable"
      :visible.sync="importdialog"
      v-el-drag-dialog
      @close=importdialogclose
      width="70%">
      <el-table stripe border @selection-change="handleSelectionChange" :data="importList" height='500' style="width: 100%; margin-top: 15px;padding-bottom:15px;">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
        <el-table-column label="申请人员" prop="Name" align="left" width="120px"></el-table-column>
        <el-table-column label="邮箱" prop="Account" align="left"></el-table-column>
        <el-table-column label="密码" prop="Pwd" align="left"></el-table-column>
        <el-table-column label="邮箱服务器" prop="SmtpServer" align="left" ></el-table-column>
        <el-table-column label="是否加密（0：不加密，1：加密）" prop="IsOpenSSL" align="left" ></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importdialog = false;">取 消</el-button>
        <el-button type="primary" @click="submitImport()">确认导入</el-button>
      </span>
    </el-dialog>
    <el-dialog
      top="5vh"
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="海关编码"
      :visible.sync="codingDialog"
      v-el-drag-dialog
      width="80%">
      <el-tree
        accordion
        :data="HSCodeList"
        node-key="HsCode"
        @node-click="checkChange"
        :props="{ label:'Name', value:'HsCode', children: 'Child', expandTrigger: 'hover' }">
        <template slot-scope="{node, data}">
          <el-tooltip effect="dark" :content="data.tooltip" placement="top-start" style="font-size:14px;">
          <span>{{node.label}}<span v-if="data.HsCode">  (品目编码：{{ data.HsCode}})</span></span>
          </el-tooltip>
        </template>
      </el-tree>
      
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="codingDialog = false;">关 闭</el-button>
        <el-button type="primary" @click="submitCode()">确认</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      top="5vh"
      title="请选择国家"
      :visible.sync="countryDialog"
      v-el-drag-dialog
      width="90%">
      <div style="display: flex;">
        <div>
          <div style="color:#2491fc;"><span style="display:inline-block;width:15px;height:15px;background:#2491fc;border-radius:50%;margin-right:5px;margin-bottom:-3px;"></span>商品国家选择</div>
          <div style="display:flex;flex-wrap:wrap;width:100%;">
            <div v-for="(item, index) in CountrysList" :key="index" style="width:130px;height:40px;display:flex;align-items:center;margin-right:5px;cursor: pointer;" @click="outCountryClick(item.Country)">
              <span v-show="!outCountry.includes(item.Country)" style="display:inline-block;width:15px;height:15px;background:#ccc;border-radius:50%;margin-right:5px;flex-shrink: 0;"></span>
              <span v-show="outCountry.includes(item.Country)" class="el-icon-success" style="margin-right:5px;flex-shrink: 0;color:#2491fc;font-size:16px;"></span>
              <el-image :src="item.flag" style="height:15px;margin:0 5px;"></el-image>
              <div style="font-size:13px;">{{ item.Country }}</div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCounyry">确 定</el-button>
        <el-button type="info" @click="countryDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="请选择详细分类"
      :visible.sync="classDialog"
      v-el-drag-dialog
      width="50%">
      <div style="display: flex;">
        <div style="margin-top: -10px;">
          <div style="color:#2491fc;"><span style="display:inline-block;width:8px;height:15px;background:#2491fc;border-radius:5px;margin-right:5px;margin-bottom: -3px;"></span>分类选择</div>
          <div style="margin-top:10px;">
            <el-radio style="width: 120px;margin-bottpm:5px;margin-top:5px;" v-model="resourceForm.Class" v-for="(item, key) in ExpoClassList" :key="key" :label="item">{{ item }}</el-radio>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitClass">确 定</el-button>
        <el-button type="info" @click="classDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    
  </div>
</template>
<script>
import { connrequest, downloadfile } from '@/api/firstPage'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import XLSX from 'xlsx'
import { getuuid, parseTime } from '@/utils'
import { load } from 'jszip/lib/object'
import massPostingAccount from './massPostingAccount'
import intelligentMassSending from './intelligentMassSending'
import historicalSoftWriting from './historicalSoftWriting'
export default {
name:'mailResources',
directives: { elDragDialog },
components: { massPostingAccount, intelligentMassSending, historicalSoftWriting },
data() {
  return {
    HSCodeList: [],
    value:'',
    ExpoClassList: [],
    ExpoCountryList: [],
    isTestMail: true,
    correct: '',
    abnormal: '',
    percentage: 0,
    loading: false,
    loadingtext: false,
    pageNum: 1,
    pageSize: 10,
    total: 10,
    tableData: [],
    emailForm: {},
    emailList: [],
    importList:[],
    choseList:[],
    CountrysList: [],
    outCountry: [],
    dialogVisible: false,
    importdialog: false,
    codingDialog: false,
    countryDialog: false,
    classDialog: false,
    formshow:true,
    IsActivePwd: 0,
    rules: {
      // Country: [
      //   { required: true, message: "请选择国家", trigger: 'change'},
      // ],
      // Class: [
      //   { required: true, message: "请选择详细分类", trigger: 'change'},
      // ],
      // HSCode: [
      //   { required: true, message: "请输入海关HS编码", trigger: 'change'},
      // ],
      // OutCountry: [
      //   { required: true, message: "请选择出口商国家", trigger: 'change'},
      // ],
      // InCountry: [
      //   { required: true, message: "请选择进口商国家", trigger: 'change'},
      // ],
    },
    resourceForm: {
      ResType: 1,
      Country: "",
      Class: "",
      Duty: [],
			Year:''
    },
		yearList:[],
    Action: 1,
    testmail:'',
    CargoForm:{
      Cname:''
    },
    CargoDialog:false,
    CargoList:[], 
    control:false
		
  }
},
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    // this.getData()
    this.GetParamMailGlobal()
    this.GetEMailADTask()
    this.GetDetailFileContent()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    // this.GetEMailSmtpCfg()
	const currentYear = new Date().getFullYear();
	for(var i = 0; i<10;i++)
		this.yearList[i] = currentYear-i
  },
  methods: {
    radioChange(val){
      if(val === 3){
        this.value = ['全部','全部']
      }
    },
    concelCargo(){
      this.dialogVisible = false
      this.value = []
    },
    tabClick(row){
      switch (row.label) {
        case '基本参数':
          this.GetParamMailGlobal()
          break;
        case '客户群体':
          this.GetEMailADTask()
          break;
        case '智能群发':
          this.$refs.intelligentMassSending.GetParamMailADGlobal()
          this.$refs.intelligentMassSending.GetEMailResList()
          break;
        case '群发帐号':
          this.$refs.massPostingAccount.getData()
          this.$refs.massPostingAccount.GetEMailSmtpCfg()
          break;
        case '历史软文':
          this.$refs.historicalSoftWriting.getData()
          break;
        default:
          break;
      }
    },
    openCountryDialog(type){
      this.outCountry = []
      this.countryDialog = true
      this.ChoseCountrytype = type
    },
    submitCounyry(){
      if(this.outCountry.length < 1){
        this.$message.error('请选择国家')
        return false
      }
      switch (this.ChoseCountrytype) {
        case 1:
          this.$set(this.resourceForm, 'Country', this.outCountry[0])
          break;
        case 2:
          this.$set(this.resourceForm, 'OutCountry', this.outCountry[0])
          break;
        default:
          this.$set(this.resourceForm, 'InCountry', this.outCountry[0])
          break;
      }
      this.countryDialog = false
    },
    submitClass(){
      this.classDialog = false
    },
    handleChange(value){
      // console.log(value);
    },
    handleChanges(value){
      if(value[0] !== '全部')
        this.control = true
      else
        this.control = false
    },
    checkChange(node){
      if(node.HSCode){
        this.HsCode = node.HSCode
      }
    },
    viewClassificationCodes(){
      this.HsCode = ''
      this.codingDialog = true
    },
    viewClassCargo(){
      // this.HsCode = ''
      this.CargoDialog = true
    },
    submitCode(){
      if(this.HsCode !== ''){
        this.$set(this.resourceForm, 'HSCode', this.HsCode)
      }else{
        this.$message.info('请选择品目编码')
      }
    },
    outCountryClick(country){
      if (this.outCountry.length < 1 && !this.outCountry.includes(country)) {
        this.outCountry.push(country);
      } else if (this.outCountry.includes(country)) {
        let index = this.outCountry.indexOf(country);
        this.outCountry.splice(index, 1);
      } else {
        this.$message.info('请选中不超过一个国家');
      }
    },
    async GetDetailFileContent(){
      const data = {
        Data:{
          FileName: '/school/config/national_flag_img.json'
        }
      }
      const res = await connrequest('GetDetailFileContent', data)
      let array = JSON.parse(res.Data.Content);
      const CountrysList = Object.entries(array).map(([country, flag]) => ({ Country: country, flag: `${process.env.VUE_APP_BASE_API}/national_flag_img/${flag}` }));
      this.CountrysList = [...CountrysList]
    },
    async GetEMailADTask(){
      const res = await connrequest('GetEMailADTask')
      res.Data.map(item => {
        item.Duty = item.Duty ? item.Duty.split('') : []
      })
      this.tableData = res.Data
    },
    importResources(){
      this.$refs.upfile.click()
    },
    handleSelectionChange(val){
      this.choseList = val
    },
    AccountChange(row){
      let mail = row.split("@")[1]
      this.$set(this.emailForm, 'SmtpServer', this.emailList.find( item => item.Mail === mail)?.SmtpServer || '')
      this.emailchange(this.emailList.find( item => item.Mail === mail))
    },
    async GetEMailSmtpCfg(){
      const res = await connrequest('GetEMailSmtpCfg')
      res.Data = res.Data || []
      res.Data.map(item=>{
        item.value = item.SmtpServer
      })
      this.emailList = [...res.Data]
      let mail = this.emailForm.FromAccount ? this.emailForm.FromAccount.split("@")[1] : ''
      this.emailchange(this.emailList.find( item => item.Mail === mail))
    },
    submitImport(){
      let success = 0
      let flag = 0;
      if(this.choseList.length === 0){
        this.$message.success('请先选择要导入的人员')
        return false
      }
      else{
        this.choseList.map(item=>{
          item.IsOpenSSL = item.IsOpenSSL === '加密' ? 1 : 0
          return item
        })
        this.choseList.forEach(async(item) => {
          let Detail = item
          const data = {
            Data:{
              Action: 1,
              Detail: {
                ...Detail,
                Status: 0
              }
            }
          }
          const res = await connrequest('EditMailAccounts', data)
          flag++
          if(res.Status.StatusCode === 0){
            success++
          }
          if(flag === this.choseList.length){
            this.$message({
              showClose: true,
              duration: 7000,
              type: success == this.choseList.length ? 'success' : 'error',
              message: `导入成功${success}个，失败${this.choseList.length - success}个`
            });
            this.importdialog = false
            this.$refs.upfile.value = ''
            this.getData()
          }
        })
      }
    },
    importdialogclose(){
      this.choseList = []
      this.$refs.upfile.value = ''
    },
    async DownloadFile(){
      const data = {
        Data:{
          FileName: '邮件资源模板.xlsx'
        }
      }
      const res = await downloadfile('DownloadPublicFile', data)
      let blobUrl = window.URL.createObjectURL(new Blob([res]));
      const a = document.createElement('a');
      a.style.display = 'none';
      a.download = '邮件资源模板.xlsx';
      a.href = blobUrl;
      a.click();
    },
    changefile(e){
      this.choseList = []
      // 读取表格文件
      let that = this;
      const files = e.target.files;
      if (files.length <= 0) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$message({
          message: "上传格式不正确，请上传xls或者xlsx格式",
          type: "warning"
        });
        return false;
      } else {
        // 更新获取文件名
        that.upload_file = files[0].name;
      }
      const fileReader = new FileReader();
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary"
          });
          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          this.da = [...ws]
          let arr = []
          this.da.map(v => {
            let obj = {}
            obj.Name = v['申请人员']
            obj.Account = v['邮箱']
            obj.Pwd = v['密码（需要开通SMTP一些邮件服务器需要为激活密码）']
            obj.SmtpServer = v['邮箱服务器']
            obj.IsOpenSSL = v['是否加密（0：不加密，1：加密）']
            arr.push(obj)
          })
          this.importList = [...arr]
          this.importList = this.unique(this.importList)  //删除exl的重复数据
          this.tableData.forEach(item => {  //删除和tableData重复数据
            this.importList = this.importList.filter(newitem => {
              return newitem.Account !== item.Account
            })
          })
          const email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
          this.importList = this.importList.filter(item => {
            return email.test(item.Account)
          })
          this.importdialog = true
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    unique(arr){
      var obj = {};
      var newArr = arr.reduce((prev,cur)=>{
        obj[cur.Account] ? '':obj[cur.Account] = true && prev.push(cur);
        return prev
      },[]);
      return newArr
    },
    querySearch(queryString, cb) {
      var restaurants = this.emailList;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    querySearch2(queryString, cb) {
      let arr = []
      for (var i = 1; i <= 24; i++){
        arr.push({value: `${i}:00`})
      }
      var restaurants = arr;
      var results = queryString ? restaurants.filter(this.createFilter2(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter2(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    emailchange(row){
      this.$set(this.emailForm, 'IsOpenSSL', row?.IsOpenSSL || 0)
      this.IsActivePwd = row?.IsActivePwd || 0
    },
    async addResources(){
      if(this.tableData.length >= 10){
        this.$message.info('最大配置10个目标客户群体')
        return false
      }
      await this.receiveInformation()
      this.Action = 1
      this.resourceForm = { ResType: 1, Duty:['老板','管理人员','采购','其他']}
      this.$nextTick(()=>{
        this.$refs['resourceForm'].clearValidate()
      })
      this.dialogVisible = true
    },
    changeMailGlobal(row){
      this.Action = 2
      this.resourceForm = {...row}
      this.resourceForm.IsOpenSSL = row.IsOpenSSL === '加密' ? 1 : 0
      this.dialogVisible = true
    },
    deleteMailGlobal(row){
      this.Action = 3
      this.resourceForm = {...row}
      this.$confirm('此操作将删除项目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data:{
            Action: this.Action,
            Detail: {
              ...this.resourceForm
            }
          }
        }
        const res = await connrequest('EditEMailADTask', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('删除成功')
          this.dialogVisible = false
          this.GetEMailADTask()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    }, 
    async GetParamMailGlobal(){
      const res = await connrequest('GetParamMailADGlobal')
      // const testmail = await connrequest('GetParamMailGlobal')
      // this.testmail = testmail.Data.ToAccount
      this.emailForm = {...res.Data}
      // const res1 = await connrequest('GetFreightClass')
    },
    async receiveInformation(){
      const HSCode = await connrequest('GetHSCode')
      const ExpoClass = await connrequest('GetExpoClass')
      const ExpoCountry = await connrequest('GetExpoCountry')
      this.HSCodeList = this.setTooltip(HSCode.Data)
      const CargoClass = await connrequest('GetFreightClass')
      this.CargoList = CargoClass.Data
      let newLi ={"Name":"全部","value":"全部",Child:[]}
      this.CargoList.unshift(newLi)
      // this.CargoList.unshift(newLi)
      // this.CargoDialog.insert(0,li)
      this.CargoList.map(item =>{
        item.value = item.Name
        
        // item.Chile.Name = '全部'
        // item.Chile.value = '全部'
        let li ={"Name":"全部","value":"全部"} 
        item.Child = item.Child.map(it=>({Name: it,value:it}))
        item.Child.unshift(li)
      })
      
      this.ExpoClassList = ExpoClass.Data
      this.ExpoCountryList = ExpoCountry.Data
    },
    setTooltip(treeData){
      treeData.forEach(node => {
        if (node.HsCode) {
          node.tooltip = `${node.Name} (品目编码：${node.HsCode})`;
        } else {
          node.tooltip = node.Name;
        }
        if (node.Child) {
          this.setTooltip(node.Child);
        }
      })
      return treeData
    },
    async getData() {
      const res = await connrequest('GetMailDstCustomClass')
      res.Data = res.Data || []
      res.Data.map( item =>{
        item.IsOpenSSL = item.IsOpenSSL === 1 ? '加密' : '不加密'
        item.LastCheckTime = parseTime(item.LastCheckTime)
        return item
      })
      this.tableData = res.Data
    },
    async SetParamMailGlobal(){
      let SendInterval = /^[0-9]*$/ 
      let email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      let regPwd = /^[^\u4e00-\u9fa5 ]{0,}$/
      if(!SendInterval.test(this.emailForm.ExecHours) && this.emailForm.ExecHours* 1 > 24){
        this.$message.error('邮件推广执行时间点只能为小于24的数字')
      }
      else if(!SendInterval.test(this.emailForm.SendInterval)){
        this.$message.error('邮件发送延迟只能为数字')
      }
      // else if(!SendInterval.test(this.emailForm.MaxCountPerDay)){
      //   this.$message.error('最大发送邮件数量只能为数字')
      // }
      else if(this.emailForm.DefaultEMailAccountFormat === ''){
        this.$message.error('默认邮箱前缀不能为空')
      }else if(this.emailForm.DefaultSMTPServer === ''){
        this.$message.error('默认邮箱服务器不能为空')
      }else if(this.emailForm.DefaultEMailPwd === ''){
        this.$message.error('默认邮箱密码不能为空')
      }else if(!regPwd.test(this.emailForm.DefaultEMailPwd)){
        this.$message.error('默认邮箱密码不能有中文或空格')
      }else{
        this.emailForm.ExecHours = this.emailForm.ExecHours * 1
        this.emailForm.SendInterval = this.emailForm.SendInterval * 1 || 0
        this.emailForm.MaxCountPerDay = this.emailForm.MaxCountPerDay * 1 || 0
        this.emailForm.StartEMailCount = this.emailForm.StartEMailCount * 1 || 0
        this.emailForm.IncreateCountPerDay = this.emailForm.IncreateCountPerDay * 1 || 0
        const data = {
          Data:{
            ...this.emailForm
          }
        }
        const res = await connrequest('SetParamMailADGlobal', data)
        if(res.Status.StatusCode === 0){
          this.$message.success('保存成功')
          this.GetParamMailGlobal()
        }
      }
    },
    calculatePermissions(selectedOptions) {
      const options = ['老板', '管理人员', '采购', '其他'];
      let binaryString = '';
      for (const option of options) {
        if (selectedOptions.includes(option)) {
          binaryString += '1';
        } else {
          binaryString += '0';
        }
      }
      return binaryString;
    },
    submit(){
      this.$refs['resourceForm'].validate(async (valid) => {
        if(valid){
          let isDuplicate = this.tableData.some(obj => {
            return obj.ResType === this.resourceForm.ResType &&
                  obj.Country === this.resourceForm.Country &&
                  obj.Class === this.resourceForm.Class;
          });
          let isDuplicate2 = this.tableData.some(obj => {
            return obj.HSCode === this.resourceForm.HSCode &&
                    obj.ResType === this.resourceForm.ResType &&
                  obj.OutCountry === this.resourceForm.OutCountry &&
                  obj.InCountry === this.resourceForm.InCountry;
          });
          if((isDuplicate && this.resourceForm.ResType === 1) || (isDuplicate2 && this.resourceForm.ResType === 2)){
            this.$message.error('已存在相同的用户群体')
            return false
          }
          let resourceForm = this. resourceForm
          if(resourceForm.ResType === 2 && !resourceForm.HSCode && !resourceForm.OutCountry && !resourceForm.InCountry){
            this.$message.error('请填写海关HS编码或选择进口/出口国家')
            return false
          }
          if(resourceForm.ResType === 2 && resourceForm.HSCode && resourceForm.HSCode.length !== 4){
            this.$message.error('请输入4位数字的海关HS编码')
            return false
          }
          if(resourceForm.Duty.length === 0 ){
            this.$message.error('请至少选择一个公司职位')
            return false
          }
          this.resourceForm
          const data = {
            Data:{
              Action: this.Action,
              Detail: {
                ...this.resourceForm,
                Duty: this.calculatePermissions(resourceForm.Duty),
                TaskID: getuuid()
              }
            }
          }
          const res = await connrequest('EditEMailADTask', data)
          if(res.Status.StatusCode === 0){
            this.Action === 1 ? this.$message.success('添加成功') : this.$message.success('修改成功')
            this.dialogVisible = false
            this.GetEMailADTask()
          }
        }
      })
    },
    async submitCargo(){
      if(this.value[0] === undefined)
        {
          let li= ['全部','全部']
          this.value = li
          
        }  
      const data = {
            Data:{
              Action: 1,
              Detail: {
                ResType:3,
                Class: this.value[0],
                CorpType: this.value[1],
                TaskID: getuuid()
              }
            }
          }
          // console.log("提交数据",data)
          const res = await connrequest('EditEMailADTask', data)
          if(res.Status.StatusCode === 0){
            this.$message.success('添加成功') 
            this.dialogVisible = false
            this.GetEMailADTask()
          }
          this.value = []
    },
    async TestMailGlobal(row,status,flag = true){
      // const loading = this.$loading({
      //   lock: true,
      //   text: "加载中……",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
      const ParamMailGlobal = await connrequest('GetParamMailGlobal')
      if(!ParamMailGlobal.Data.ToAccount){
        this.$message.error('发送测试邮箱失败，请在邮件通知->参数配置界面配置好接收邮箱再进行测试')
        return false
      }
      this.loading = true
      try{
      let IsOpenSSL
      if(status === 1){
        IsOpenSSL = row.IsOpenSSL
      }
      if(status === 2){
        IsOpenSSL = row.IsOpenSSL === '加密' ? 1 : 0
      }
      const data = {
        Data:{
          FromAccount: row.ToAccount || row.Account,
          Pwd: row.Pwd,
          SmtpServer: row.SmtpServer,
          IsOpenSSL: IsOpenSSL,
          IsAddCorpNameToSendAccount: this.emailForm.IsAddCorpNameToSendAccount,
          SendNickName: this.emailForm.SendNickName,
          ToAccount: this.testmail
        },
        Header: {
          showLoading: flag
        }
      }
      const res = await connrequest('TestMailGlobal', data)
      if(res.Status.StatusCode === 0){
        this.correct++
        this.$message.success('发送测试邮件正常')
      }else{
        this.abnormal++
        this.$message.error('邮箱测试异常，发送测试邮件失败')
      }
      // loading.close()
      this.loading = false
      flag && this.getData()
      }catch(e){
      this.loading = false
        // loading.close()
      }
    },
    async TestAllMailGlobal(){
      this.percentage = 0
      const { tableData } = this
      this.loadingtext = false
      this.correct = 0
      this.abnormal = 0
      // const loading = this.$loading({
      //   lock: true,
      //   text: "加载中……",
      //   background: "rgba(0, 0, 0, 0.7)",
      // });
      let num = 100 / tableData.length
      for (let i = 0; i < tableData.length; i++) {
        if (!this.isTestMail) return
        await this.TestMailGlobal(tableData[i], 2, false)
        this.percentage = this.percentage + num
      }
      // loading.close()
      this.loadingtext = true
      this.getData()
    },
    handleSizeChange(){},
    handleCurrentChange(){}
  },
  beforeDestroy () {
    this.isTestMail = false
  }
}
</script>
<style lang="scss" scoped>
/* @import url(); 引入css类 */
@import "~@/styles/variables.scss";
.parameType .title{
  border: none !important;
}
.el-progress{
  margin-top: 7px;
  width:100%;
}
.content {
  margin-top: 0;
  width: 800px;
  position: relative;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .title{
    margin-bottom: 10px;
    border: none;
    cursor: pointer;
  }
  ::v-deep .certification{
    .toptitle{
      display: flex;
      // border-bottom: 1px solid #eceff5;
      // align-items: center;
      justify-content: space-between;
      // i{
      //   color: #409EFF;
      //   cursor: pointer;
      // }
    }
    .el-form-item{
      margin-bottom: 10px;
    }
    .el-col{
      display: flex;
      align-items: center;
      p{
        width: 100px;
        display:block;
        color: #aaa;
        font-size: 12px;
        padding-left: 20px;
        white-space: nowrap;
      }
    }
  }
}
.top{
  flex-wrap: nowrap;
}
.btn{
  margin: 20px 0;
  display: flex;
  align-items: center;
  .percentage{
    width: 350px;
    margin-left: 20px;
  }
}
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;
    .name {
      text-overflow: ellipsis;
      overflow: hidden;
      line-height: 14px !important;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }
    .highlighted .addr {
      color: #ddd;
    }
  }
}

.tabclick{
  display: flex;
  height: 20px;
  justify-content: center;
  margin-top: 0px;
  .tabitem{
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content:center;
    padding: 2px 10px;
    width: 90px;
    font-size: 12px;
    color: #bbb;
    border-radius: 4px;
    border: 1px solid #ebeef5;
    margin-right: 10px;
    transform:  perspective(2em) rotateX(-20deg);
    span{
      transform:  perspective(2em) rotateX(10deg);
    }
  }
}
.tabclick :hover{
  background: #f7f7f7;
}
</style> 